<!doctype html>
<html lang="zh-Hans">
	<head>
		<title>LED限流电阻计算器 - 嵌入式工具集</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<!-- 引入Tailwind CSS -->
		<script src="https://cdn.tailwindcss.com"></script>
		<!-- 以下为浏览器中的配置，正式 编译之后请注释掉这段-->
		<link rel="stylesheet" href="../styles/styles.css" />
		<!-- 以下为LCEDA中的配置，正式 编译之后请勿注释这段-->
		<link rel="stylesheet" href="/iframe/styles/styles.css" />
		<style>
			/* LED电阻计算器特定样式覆盖 */
			.led-resistor-calculator .input-label {
				min-width: 140px;
			}

			/* 图标样式 - 确保在嘉立创EDA环境中正常显示 */
			.fa {
				display: inline-block;
				width: 1em;
				height: 1em;
				font-size: inherit;
				line-height: 1;
				vertical-align: middle;
				text-align: center;
			}

			.fa-calculator:before {
				content: '🧮';
				font-size: 1.2em;
			}

			.fa-refresh:before {
				content: '↺';
				font-size: 1.2em;
			}

			.fa-info-circle:before {
				content: 'ℹ️';
				font-size: 1.1em;
			}

			/* 增强按钮样式 - 与其他计算器保持一致 */
			.btn-primary {
				background-color: #0891b2;
				color: white;
				border: none;
				border-radius: 8px;
				padding: 0.75rem;
				cursor: pointer;
				transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
				font-weight: 600;
				font-size: 1rem;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
				height: 3.5rem;
			}

			.btn-primary:hover:not(.bg-gray-400) {
				background-color: #0e7490;
				transform: translateY(-2px);
				box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
			}

			.btn-secondary {
				background-color: #f59e0b;
				color: white;
				border: none;
				border-radius: 8px;
				padding: 0.75rem;
				cursor: pointer;
				transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
				font-weight: 600;
				font-size: 1rem;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
				height: 3.5rem;
			}

			.btn-secondary:hover {
				background-color: #d97706;
				transform: translateY(-2px);
				box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
			}

			/* 优化公式框样式 */
			.formula-box {
				background-color: #f8fafc;
				border-radius: 12px;
				padding: 1.5rem;
				margin-bottom: 1.5rem;
				font-family: 'SF Pro Text', 'Inter', monospace;
				text-align: center;
				border: 1px solid #e2e8f0;
				box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
				transition: all 0.3s ease;
			}

			.formula-box:hover {
				box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
				transform: translateY(-1px);
			}

			.formula-title {
				font-weight: 700;
				margin-bottom: 0.75rem;
				color: #374151;
				font-size: 1.1rem;
				letter-spacing: 0.025em;
			}

			.formula-text {
				color: #4b5563;
				font-size: 0.95rem;
				line-height: 1.7;
			}

			/* 优化结果卡片样式 */
			.result-cards {
				display: grid;
				grid-template-columns: repeat(2, 1fr);
				gap: 1.25rem;
				margin: 1.5rem 0;
			}

			.result-card {
				border-radius: 12px;
				padding: 1.5rem;
				text-align: center;
				transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
				color: white;
				position: relative;
				overflow: hidden;
			}

			.result-card:hover {
				transform: translateY(-5px) scale(1.03);
				box-shadow:
					0 20px 25px -5px rgba(0, 0, 0, 0.1),
					0 10px 10px -5px rgba(0, 0, 0, 0.04);
			}

			/* 特定结果卡片颜色 */
			.resistance-card {
				background: linear-gradient(135deg, #fde68a 0%, #fcd34d 100%);
				color: #92400e;
				box-shadow: 0 10px 25px -5px rgba(245, 158, 11, 0.3);
				border: 1px solid rgba(255, 255, 255, 0.3);
			}

			.current-card {
				background: linear-gradient(135deg, #6ee7b7 0%, #34d399 100%);
				color: #065f46;
				box-shadow: 0 10px 25px -5px rgba(16, 185, 129, 0.3);
				border: 1px solid rgba(255, 255, 255, 0.3);
			}

			.power-card {
				background: linear-gradient(135deg, #c4b5fd 0%, #a78bfa 100%);
				color: #5b21b6;
				box-shadow: 0 10px 25px -5px rgba(139, 92, 246, 0.3);
				border: 1px solid rgba(255, 255, 255, 0.2);
			}

			.standard-card {
				background: linear-gradient(135deg, #93c5fd 0%, #60a5fa 100%);
				color: #1e40af;
				box-shadow: 0 10px 25px -5px rgba(59, 130, 246, 0.3);
				border: 1px solid rgba(255, 255, 255, 0.3);
			}

			/* 卡片标题和值样式 */
			.result-title {
				font-size: 0.9rem;
				opacity: 0.95;
				margin-bottom: 0.75rem;
				font-weight: 600;
				letter-spacing: 0.025em;
			}

			.result-value {
				font-size: 1.5rem;
				font-weight: 700;
				margin-bottom: 0.5rem;
				text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
				font-family: 'SF Pro Text', 'Inter', sans-serif;
				font-weight: 800;
			}

			/* 卡片单位样式 */
			.result-unit {
				font-size: 0.85rem;
				opacity: 0.85;
				font-weight: 500;
			}
		</style>
	</head>
	<body class="bg-gradient-to-br from-light to-blue-50 min-h-screen p-6 font-sans">
		<div class="w-full mx-auto bg-white rounded-2xl shadow-lg p-6 calculator-container led-resistor-calculator">
			<h2 class="text-xl md:text-2xl font-bold text-primary mb-6 text-center">LED串联电阻计算器</h2>

			<div class="formula-box">
				<div class="formula-title">LED限流电阻计算公式</div>
				<div class="formula-text">R = (Vcc - Vf) / If</div>
				<div class="formula-text">串联电阻 = (电源电压 - LED正向电压) / LED工作电流</div>
			</div>

			<div class="space-y-5">
				<div class="input-group">
					<div class="input-label">电源电压</div>
					<div class="input-field">
						<input type="number" id="vcc" placeholder="例如: 5.0" step="0.1" min="0" value="5.0" />
						<span class="input-unit">V</span>
					</div>
				</div>

				<div class="input-group">
					<div class="input-label">LED正向电压</div>
					<div class="input-field">
						<input type="number" id="vf" placeholder="例如: 2.0" step="0.1" min="0" value="2.0" />
						<span class="input-unit">V</span>
					</div>
				</div>
				<p class="text-xs text-gray-500 mt-1">常见值: 红色约1.8-2.2V, 绿色约2.0-2.4V, 蓝色/白色约3.0-3.6V</p>

				<div class="input-group">
					<div class="input-label">LED工作电流</div>
					<div class="input-field">
						<input type="number" id="if" placeholder="例如: 20" step="1" min="1" value="20" />
						<span class="input-unit">mA</span>
					</div>
				</div>
				<p class="text-xs text-gray-500 mt-1">常见小功率LED推荐电流: 10-20mA</p>

				<!-- 操作区域 -->
				<div class="flex items-center space-x-3 mt-2">
					<!-- 实时更新选择框 -->
					<div class="flex items-center space-x-2 bg-gray-50 p-3 rounded-lg border border-gray-100">
						<input type="checkbox" id="live-calculation" checked />
						<label
							for="live-calculation"
							class="text-sm font-medium text-gray-700 cursor-pointer flex items-center justify-center h-full"
						>
							实时更新
						</label>
					</div>

					<!-- 计算按钮 -->
					<button onclick="ledCalculate()" id="calculate-button" class="btn-primary flex-1">
						<i class="fa fa-calculator mr-2"></i>计算电阻
					</button>

					<!-- 重置按钮 -->
					<button onclick="ledClear()" class="btn-secondary flex-1"><i class="fa fa-refresh mr-2"></i>重置</button>
				</div>

				<!-- 结果显示区域 -->
				<div id="led-result" class="hidden">
					<div class="result-cards">
						<div class="result-card resistance-card">
							<div class="result-title">理论电阻值</div>
							<div class="result-value" id="result-resistance">0</div>
							<div class="result-unit">Ω</div>
						</div>

						<div class="result-card standard-card">
							<div class="result-title">标准电阻值</div>
							<div class="result-value" id="result-standard">0</div>
							<div class="result-unit">Ω</div>
						</div>

						<div class="result-card current-card">
							<div class="result-title">实际电流</div>
							<div class="result-value" id="result-current">0</div>
							<div class="result-unit">mA</div>
						</div>

						<div class="result-card power-card">
							<div class="result-title">建议功率</div>
							<div class="result-value" id="result-power">0</div>
							<div class="result-unit">mW</div>
						</div>
					</div>

					<!-- 详细结果信息 -->
					<div class="mt-4 p-4 bg-blue-50 rounded-lg text-blue-700 font-medium text-center border border-blue-100">
						<div id="result-details"></div>
					</div>
				</div>
			</div>

			<div class="info-box mt-6">
				<div class="info-title">计算说明</div>
				<ul class="info-list">
					<li><i class="fa fa-info-circle mr-1"></i>计算结果给出理论值和最接近的标准电阻值</li>
					<li><i class="fa fa-info-circle mr-1"></i>串联电阻用于限制LED的电流，防止LED过流损坏</li>
					<li><i class="fa fa-info-circle mr-1"></i>计算出的电阻功率应大于等于计算功率的1.5-2倍</li>
				</ul>
			</div>
		</div>

		<script>
			// LED串联电阻计算
			function ledCalculate() {
				const vcc = parseFloat(document.getElementById('vcc').value);
				const vf = parseFloat(document.getElementById('vf').value);
				const if_mA = parseFloat(document.getElementById('if').value); // 电流单位为mA
				const resultDiv = document.getElementById('led-result');

				// 验证输入
				if (isNaN(vcc) || isNaN(vf) || isNaN(if_mA)) {
					resultDiv.classList.remove('hidden');
					document.getElementById('result-details').innerHTML = '<p>请输入所有必要的值</p>';
					return;
				}

				// 验证电压关系
				if (vcc <= vf) {
					resultDiv.classList.remove('hidden');
					document.getElementById('result-details').innerHTML = '<p>电源电压必须大于LED正向电压</p>';
					return;
				}

				// 将mA转换为A
				const if_A = if_mA / 1000;

				// 计算理论电阻值 (R = (Vcc - Vf) / If)
				const resistance = (vcc - vf) / if_A;

				// 计算电阻功率 (P = I² × R)
				const power = if_A * if_A * resistance;

				// 查找最接近的标准电阻值（E24系列）
				const standardResistors = [
					1.0, 1.1, 1.2, 1.3, 1.5, 1.6, 1.8, 2.0, 2.2, 2.4, 2.7, 3.0, 3.3, 3.6, 3.9, 4.3, 4.7, 5.1, 5.6, 6.2, 6.8, 7.5, 8.2, 9.1,
				];

				// 计算最接近的标准电阻值
				let closestResistor = findClosestStandardResistor(resistance, standardResistors);

				// 计算使用标准电阻时的实际电流
				const actualCurrent = ((vcc - vf) / closestResistor) * 1000; // 转换为mA

				// 显示结果区域
				resultDiv.classList.remove('hidden');

				// 更新结果卡片，添加动画效果
				updateResultWithAnimation('result-resistance', resistance.toFixed(2));
				updateResultWithAnimation('result-standard', closestResistor.toString());
				updateResultWithAnimation('result-current', actualCurrent.toFixed(2));

				const recommendedPower = power * 2 * 1000;
				const recommendedPowerFormatted =
					Math.ceil(recommendedPower) > 1000 ? Math.ceil(power * 2) + 'W' : Math.ceil(recommendedPower) + 'mW';
				updateResultWithAnimation('result-power', recommendedPowerFormatted);

				// 更新详细信息
				const detailsHTML = `
                <p><strong>电阻理论功率:</strong> ${(power * 1000).toFixed(2)} mW</p>
                <p><strong>建议电阻功率:</strong> 至少 ${recommendedPower.toFixed(2)} mW</p>
            `;
				document.getElementById('result-details').innerHTML = detailsHTML;
			}

			// 查找最接近的标准电阻值
			function findClosestStandardResistor(value, standardValues) {
				// 处理小于1Ω的情况
				if (value < 1) {
					return value;
				}

				// 计算数量级（如10, 100, 1000等）
				const magnitude = Math.pow(10, Math.floor(Math.log10(value)));

				// 将值归一化到1-10范围内
				const normalizedValue = value / magnitude;

				// 找到最接近的标准值
				let closest = standardValues[0];
				let minDiff = Math.abs(normalizedValue - closest);

				for (const standard of standardValues) {
					const diff = Math.abs(normalizedValue - standard);
					if (diff < minDiff) {
						minDiff = diff;
						closest = standard;
					}
				}

				// 返回乘以数量级后的实际电阻值
				return closest * magnitude;
			}

			// 更新结果并添加动画效果
			function updateResultWithAnimation(elementId, value) {
				const element = document.getElementById(elementId);
				if (!element) return;

				// 添加更明显的过渡效果
				element.style.transition = 'all 0.3s ease-in-out';
				element.style.opacity = '0.5';
				element.style.transform = 'scale(0.95)';

				setTimeout(() => {
					element.textContent = value;
					element.style.opacity = '1';
					element.style.transform = 'scale(1)';
				}, 150);
			}

			// 重置函数
			function ledClear() {
				document.getElementById('vcc').value = '5.0';
				document.getElementById('vf').value = '2.0';
				document.getElementById('if').value = '20';
				document.getElementById('led-result').classList.add('hidden');
			}

			// 添加键盘事件监听
			document.querySelectorAll('input').forEach((input) => {
				input.addEventListener('keyup', (e) => {
					// 按下Enter键执行计算
					if (e.key === 'Enter') {
						ledCalculate();
					}
				});
			});

			// 添加实时计算事件监听
			document.addEventListener('DOMContentLoaded', function () {
				const inputs = document.querySelectorAll('input[type="number"]');
				const liveCalculationCheckbox = document.getElementById('live-calculation');
				const calculateButton = document.getElementById('calculate-button');

				// 事件处理函数，根据实时计算选项决定是否触发计算
				function handleInputChange() {
					if (liveCalculationCheckbox.checked) {
						ledCalculate();
					}
				}

				// 为输入框添加事件监听
				inputs.forEach((input) => {
					input.addEventListener('input', handleInputChange);
					input.addEventListener('change', handleInputChange);
					input.addEventListener('blur', handleInputChange);
				});

				// 更新计算按钮状态的函数
				function updateCalculateButtonState() {
					if (liveCalculationCheckbox.checked) {
						calculateButton.classList.add('opacity-50', 'cursor-not-allowed');
						calculateButton.disabled = true;
					} else {
						calculateButton.classList.remove('opacity-50', 'cursor-not-allowed');
						calculateButton.disabled = false;
					}
				}

				// 实时计算选项改变时，如果勾选了则立即计算并更新按钮状态
				liveCalculationCheckbox.addEventListener('change', function () {
					updateCalculateButtonState();
					// 无论勾选还是取消勾选，都重新计算一次
					if (this.checked) {
						ledCalculate();
					}
				});

				// 页面加载时初始化按钮状态
				updateCalculateButtonState();

				// 页面加载时如果启用了实时计算，则执行一次计算
				if (liveCalculationCheckbox.checked) {
					ledCalculate();
				}
			});

			// 暴露给父页面的接口
			window.ledCalculate = ledCalculate;
			window.ledClear = ledClear;
		</script>

		<!-- 页脚 -->
		<footer class="max-w-md mx-auto mt-8 text-center text-sm text-gray-500">
			<p>版本号: V0.0.1-20251004</p>
		</footer>
	</body>
</html>
